<template>
	<view class="u-wrap">
		<u-navbar
		    title-color="#303133"
		    :is-fixed="true"
		    :is-back="false"
		    :background="background"
		    :back-text-style="{color: '#303133'}"
		    :border-bottom="false"
		    >
		    <view class="slot-wrap">
		        <view class="search-wrap" @click="onSearch">
		            <u-search
		                v-model="keyword"
		                :show-action="false"
		                :height="70"
		                :action-style="{color: '#fff'}"
		                :border-color="'#fff'"
                        :disabled="true"
		            ></u-search>
		        </view>
		    </view>
		    <view class="navbar-right" slot="right" v-if="isMP" @click="onMine">
		        <view class="message-box right-item">
		            <u-icon name="dibutubiao_wode" custom-prefix="custom-icon"></u-icon>
		        </view>
		    </view>
		</u-navbar>
        <view class="top-warp">
            <u-tabs :list="categoryList" :name="'cat_name'" :current="tabIndex"  bg-color="#FA3534" active-color="#FFFFFF" inactive-color="#FFFFFF" @change="tabChangeHome"></u-tabs>
        </view>
        <view v-if="!tabIndex" style="margin-top: 80rpx;padding-bottom: 140rpx;">
            <view class="home-swiper-view">
                <view class="background-view"></view>
                <view class="home-swiper">
                    <u-swiper :list="banner" :height="260" :border-radius="20" @click="blockHref"></u-swiper>
                </view>
                <view class="home-category">
                    <!-- #ifdef APP-PLUS ||  H5 -->
                    <navigator :url="menu.url" v-if="menu.url !== '/pages/live-video/live-video'" hover-class="none" class="category-item" v-for="(menu, menuIndex) in menus" :key="menuIndex">
                        <u-image width="90rpx" height="90rpx" :src="menu.image"></u-image>
                        <view class="menu-title">{{ menu.navigation_name }}</view>
                    </navigator>
                    <!-- #endif -->
                    <!-- #ifdef MP-WEIXIN -->
                    <navigator :url="menu.url" hover-class="none" class="category-item" v-for="(menu, menuIndex) in menus" :key="menuIndex">
                        <u-image width="90rpx" height="90rpx" :src="menu.image"></u-image>
                        <view class="menu-title">{{ menu.navigation_name }}</view>
                    </navigator>
                    <!-- #endif -->
                </view>
            </view>
            <view class="block-view" v-if="time !== false && seckillGoodsList && seckillGoodsList.length">
                <view class="block-header">
                    <view class="block-title u-flex">
                        <view class="seckill-title">
                            限时抢购
                        </view>
                        <view class="seckill-times">
                            <text class="seckill-nth">{{timeLine.distance_time == 0 ? (onlyOne ? '距结束' : '距下轮开始') : '距开始'}}</text>
                            <text class="seckill-time">{{ times.hours }}:{{ times.minutes }}:{{ times.seconds }}</text>
                        </view>
                    </view>
                    <navigator url="/promotion-module/seckill/seckill" hover-class="none" class="more-text">
                        更多商品
                        <u-icon class="u-margin-left-8" name="arrow-right" color="#333" size="27"></u-icon>
                    </navigator>
                </view>
                <view class="goods-list-view">
                    <scroll-view scroll-x style="white-space:nowrap;">
                        <navigator :url="'/goods-module/goods?goods_id=' + goods.goods_id + '&sku_id=' + goods.sku_id" hover-class="none" class="goods-item" v-for="(goods, index) in seckillGoodsList" :key="index">
                            <view class="goods-img">
                                <image class="img" :src="goods.goods_image"></image>
                             </view>
                            <custom-price :price="goods.seckill_price" :size="30" :fontWeight="600"></custom-price>
                            <view class="original-price">
                                <text>￥{{ goods.original_price }}</text>
                            </view>
                        </navigator>
                    </scroll-view>
                </view>
            </view>
            <view v-if="floorList" class="floor-container">
                <view :class="'item-' + item.tpl_id" v-for="(item, itemIndex) in floorList" :key="itemIndex">
                    <tpl23 v-if="item.tpl_id === 23" :item="item"></tpl23>
                    <tpl24 v-if="item.tpl_id === 24" :item="item"></tpl24>
                    <tpl25 v-if="item.tpl_id === 25" :item="item"></tpl25>
                    <tpl26 v-if="item.tpl_id === 26" :item="item"></tpl26>
                    <tpl27 v-if="item.tpl_id === 27" :item="item"></tpl27>
                    <tpl28 v-if="item.tpl_id === 28" :item="item"></tpl28>
                    <tpl29 v-if="item.tpl_id === 29" :item="item"></tpl29>
                    <tpl30 v-if="item.tpl_id === 30" :item="item"></tpl30>
                    <tpl31 v-if="item.tpl_id === 31" :item="item"></tpl31>
                    <tpl32 v-if="item.tpl_id === 32" :item="item"></tpl32>
                    <tpl37 v-if="item.tpl_id === 37" :item="item"></tpl37>
                    <tpl38 v-if="item.tpl_id === 38" :item="item"></tpl38>
                    <tpl42 v-if="item.tpl_id === 42" :item="item"></tpl42>
                </view>
            </view>
        </view>
        <mescroll-item ref="mescrollItem" v-for="(tab, i) in categoryList" :key="i" :i="i" :index="tabIndex" :tabs="categoryList" :statusBarHeight="statusBarHeight"></mescroll-item>
        <u-no-network></u-no-network>
	</view>
</template>

<script>
    import * as API_Home from '@/api/home.js'
    import * as API_Goods from '@/api/goods.js'
    import * as API_Common from '@/api/common.js'
    import * as API_Promotions from '@/api/promotions.js'
    import { Foundation } from '@/ui-utils/index.js'
    import Cache,{Keys} from '@/utils/cache.js'
    import tpl23 from './templates/tpl_23.vue'
    import tpl24 from './templates/tpl_24.vue'
    import tpl25 from './templates/tpl_25.vue'
    import tpl26 from './templates/tpl_26.vue'
    import tpl27 from './templates/tpl_27.vue'
    import tpl28 from './templates/tpl_28.vue'
    import tpl29 from './templates/tpl_29.vue'
    import tpl30 from './templates/tpl_30.vue'
    import tpl31 from './templates/tpl_31.vue'
    import tpl32 from './templates/tpl_32.vue'
    import tpl37 from './templates/tpl_37.vue'
    import tpl38 from './templates/tpl_38.vue'
    import tpl42 from './templates/tpl_42.vue'
    import MescrollItem from "./mescroll-item.vue"
    import MescrollMoreMixin from "@/components/mescroll-uni/mixins/mescroll-more.js"

	export default {
        components: {
            tpl23,
            tpl24,
            tpl25,
            tpl26,
            tpl27,
            tpl28,
            tpl29,
            tpl30,
            tpl31,
            tpl32,
            tpl37,
            tpl38,
            tpl42,
        	MescrollItem
        },
        mixins: [MescrollMoreMixin],
		data() {
			return {
                keyword: '',
                //如果是小程序则隐藏
                // #ifdef MP
                isMP: false,
                background: {
                    background: '#FA3534'
                },
                // #endif
                //如果是不是小程序则展示
                // #ifndef MP
                isMP: true,
                background: {
                	background: 'url(../../../static/images/bg/bg2.png) no-repeat',
                    backgroundSize: 'cover'
                },
                // #endif
                tabIndex: 0,
                categoryList: [] ,//分类数据
                time: false, //时间
                // 时间
                times: {
                  hours: '00',
                  minutes: '00',
                  seconds: '00'
                },
                timeLine: '', //当前这一场的时刻信息
                onlyOne: false, //是否只有一场
                seckillGoodsList: [], //限时抢购商品列表
                goodsList: [], //商品列表
                banner: [], //轮播图
                menus: [], //菜单栏
                floorList: [], //楼层数据
                networkType: '' ,//网络状态
                statusBarHeight: 0,
                interval: '',
			};
		},
        async onLoad() {
            let $this = this
            //获取网络类型
            uni.getNetworkType({
                success(res) {
                    $this.networkType = res.networkType
                    if (res.networkType !== 'none') {
                        $this.init()
                    }
                }
            })
        },
        mounted (){
            const that = this;

            uni.getSystemInfo({
                success(res) {
                    const query = uni.createSelectorQuery().in(that);
                    query.select('.top-warp').boundingClientRect(data => {
                        //状态栏高度+tab距离顶部的高度+tab的高度
                        that.statusBarHeight = res.statusBarHeight + data.top + data.height
                    }).exec();
                }
            })
        },
        onShow() {
            let $this = this
            //监听网络状态变化
            uni.onNetworkStatusChange(res => {
                //监听到有网络并且第一次没有加载数据的情况下初始化数据
                if (res.isConnected && $this.networkType === 'none') {
                    $this.init()
                }
            })
            //重新进入页面后需要开始限时抢购倒计时
            if(this.$u.test.digits(this.interval)){
                this.getTimeline();
            }
        },
        /**
         * onHide()在小程序生命周期中具有监听小程序隐藏的功能，当切换页面和切换底部菜单栏时将会关闭定时器。
         */
        onHide() {
            clearInterval(this.interval)
        },
        /**
         * 生命周期函数--监听页面卸载，当切换页面和切换底部菜单栏时也会关闭定时器。
         */
        onUnload() {
            clearInterval(this.interval)
        },
        methods: {
            async init() {
                const values = await Promise.all([
                    API_Home.getFocusPictures('WAP'),
                    API_Home.getSiteMenu('MOBILE'),
                    API_Home.getFloorData('WAP'),
                    API_Goods.getCategory(),
                    API_Common.getSiteData()
                ])
                const _banner = values[0].map(item => {
                    item.image = item.pic_url
                    return item
                })
                const page_data = values[2].page_data ? JSON.parse(values[2].page_data) : []
                this.banner = _banner
                //菜单栏(支持跳转到商品详情页)
                values[1].forEach(item => {
                    if(/^\/goods\/.*/.test(item.url)) {
                        item.url = item.url.replace('/goods/','/goods-module/goods?goods_id=')
                    } else if(/^\/shop\.*/.test(item.url)) {
                        item.url = item.url.replace('/shop/','/pages/shop/shop?shop_id=')
                    } else {
                        item.url = `${item.url}`
                    }
                })
                this.menus = values[1]
                this.floorList = page_data
                //小程序发布需过滤医药及食品类目
                // const _categoryList = values[3].filter(key=> key.category_id != 85 && key.category_id != 4)
                this.categoryList = values[3]
                this.categoryList.unshift({ name: '首页', category_id: '' })
                Cache.setItem(Keys.site, values[4])
                this.getTimeline()
            },
            //获取时间段
            getTimeline(){
                API_Promotions.getSeckillTimeLine().then(response => {
                    const data = response
                    if(!data || !data.length) return
                    const res = data.sort((x,y)=>(Number(x.time_text) - Number(y.time_text)))
                    const onlyOne = res.length === 1
                    this.onlyOne = onlyOne
                    this.time = res[0].distance_time != 0 ? res[0].distance_time : onlyOne ? Foundation.theNextDayTime() : res[1].distance_time
                    this.timeLine = res[0]
                    this.startCountDown()
                    this.getSeckillTimeGoods(res[0].time_text)
                })
            },
            //开始倒计时
            startCountDown(){
              this.interval = setInterval(()=>{
                  console.log('首页倒计时、、、、、、')
                let { time } = this
                if(time <= 0){
                  clearInterval(this.interval)
                  if(this.onlyOne){
                    uni.showModal({
                      title: '提示',
                      showCancel: false,
                      confirmColor: "#FA3534",
                      content: '本轮限时抢购已结束！',
                      success(res){
                        uni.reLaunch({ url: '/pages/tabs/home/home' })
                      }
                    })
                  }else{
                    uni.showModal({
                      title: '提示',
                      showCancel: false,
                      confirmColor: "#FA3534",
                      content: '下一轮限时抢购已经开始啦！请确认查看',
                      success(res){
                        uni.reLaunch({ url: '/pages/tabs/home/home' })
                      }
                    })
                  }
                  return false
                }
                this.time -= 1
                this.times = Foundation.countTimeDown(time)
              },1000)
            },
            //获取时间段商品
            getSeckillTimeGoods(range_time){
              API_Promotions.getSeckillTimeGoods({ range_time }).then(response => {
                const { data } = response
                this.seckillGoodsList = data
              })
            },
            // 轮播图点击事件
            blockHref(index) {
                const { operation_type ,operation_param } = this.banner[index]
                switch (operation_type) {
                  // 链接地址
                  case 'URL': uni.navigateTo({ url: operation_param })
                      break
                  // 商品
                  case 'GOODS': uni.navigateTo({ url: `/goods-module/goods?goods_id=${operation_param}` })
                      break
                  // 关键字
                  case 'KEYWORD': uni.navigateTo({ url: `/goods-module/goods-list?keyword=${operation_param}` })
                      break
                  // 店铺
                  case 'SHOP': uni.navigateTo({ url: `/pages/shop/shop?shop_id=${operation_param}` })
                      break
                  // 分类
                  case 'CATEGORY': uni.navigateTo({ url: `/goods-module/goods-list?category=${operation_param}` })
                      break
                }
            },
            //搜索
            onSearch() {
                uni.navigateTo({ url: '/pages/search/search' })
            },
            //我的
            onMine() {
                uni.switchTab({ url: '/pages/tabs/mine/mine' })
            },
            //导航栏点击
            tabChangeHome(index) {
                this.tabIndex = index
            }
        }
	}
</script>

<style lang="scss" scoped>
.top-warp{
    z-index: 9990;
    position: fixed;
    top: --window-top; /* css变量 */
    left: 0;
    width: 100%;
    background-color: $u-type-error;
    height: 100rpx;
}
.slot-wrap {
    flex: 1;
    padding-left: 20rpx;
    .search-wrap {
        margin: 0 20rpx;
    }
}
.navbar-right {
    color: #FFFFFF;
    margin-right: 24rpx;
    display: flex;
    .right-item {
        position: relative;
        color: #FFFFFF;
        display: flex;
        font-size: 40rpx;
        font-weight: 600;
    }
}
.home-swiper-view {
    .background-view {
        background-color: $u-type-error;
        height: 200rpx;
        border-bottom-right-radius: 4em 0.2em;
        border-bottom-left-radius: 4em 0.2em;
    }
    .home-swiper {
        margin: 0rpx 30rpx;
        margin-top: -180rpx;
        box-shadow: 0px 20rpx 10rpx -10rpx #c0c4cc;
    }
    .home-category {
        margin: 20rpx 30rpx;
        display: flex;
        flex-direction: row;
        align-items: center;
        flex-wrap: wrap;
        a {
            color: #303133;
            text-decoration:none;
        }
        .category-item {
            display: flex;
            align-items: center;
            flex-direction: column;
            width: 20%;
            margin-top: 10rpx;
            .menu-title {
                margin-top: 10rpx;
                font-size: 22rpx;
            }
        }
    }
}
.floor-container{
    margin: 10rpx 20rpx 20rpx 20rpx;
    border-radius: 10rpx;
    overflow: hidden;
}
.block-view {
    background-color: #fff;
    margin: 10rpx 20rpx 20rpx 20rpx;
    border-radius: 10rpx;
    padding: 10rpx 15rpx;
    .block-header {
        font-size: 31rpx;
        padding: 20rpx 0rpx;
        display: flex;
        align-items: center;
        flex-direction: row;
        justify-content: space-between;
        .seckill-title {
            font-weight: 600;
            font-size: 34rpx;
        }
        .seckill-times {
            margin: 0 20rpx;
            font-size: 22rpx;
            .seckill-nth {
                color: #fff;
                padding: 4rpx 10rpx;
                border-top-left-radius: 30rpx;
                border-bottom-left-radius: 30rpx;
                background-color: #FA3534;
                border: 2rpx solid #FA3534;
            }
            .seckill-time {
                color: #FA3534;
                font-weight: 600;
                padding: 4rpx 10rpx;
                border-top-right-radius: 30rpx;
                border-bottom-right-radius: 30rpx;
                border: 2rpx solid #FA3534;
            }
        }
        .more-text {
            color: #909399;
            font-size: 25rpx;
        }
    }
    .goods-list-view {
        .goods-item {
            width: 20%;
            display: inline-block;
            background: #fff;
            margin: 8rpx;
            border-radius: 10rpx;
            text-align: center;
            .goods-img {
                width: 120rpx;
                height: 120rpx;
                .img {
                    width: 100%;
                    height: 100%;
                }
            }
            .original-price {
                color: #ABABAB;
                font-size: 22rpx;
                line-height: 24rpx;
                margin-bottom: 15rpx;
                padding: 0 4rpx;
                text-decoration: line-through;
            }
        }
    }
}
</style>